const {Controller}=require("egg")

const {createToken}=require("../utils/utils")
const {sendMail}=require("../utils/sendMail")

const path=require("path")
const fs=require("fs")

class codeController extends Controller{

    async upLoad(){
        const {ctx}=this
        const file = ctx.request.files[0];
        const name = '1907c/'+new Date()*1 + path.basename(file.filename);
        let result;
        try {
        result = await ctx.oss.put(name, file.filepath);
        } finally {
            await fs.unlinkSync(file.filepath);
        }
    
        if (result) {
            if(result.res.status==200){
                const res=await ctx.service.codes.upLoad({
                    id:ctx.request.query.id,
                    imgurl:result.url
                })
                if(res.affectedRows){
                    ctx.body={
                      code:"1001",
                      msg:"oss上传成功",
                      imgurl:result.url
                    }
                  }else{
                    ctx.body={
                      code:"1002",
                      msg:"oss上传失败"
                    }
                  }
            }
        } else {
            ctx.body = 'please select a file to upload！';
        }
    }

    async sendMail(){
        const {ctx}=this
        const {email}=ctx.request.body
        const result=await sendMail(email)
        if(result.code==200){
            ctx.body={
                code:"1001",
                msg:"邮箱发送成功"
            }
        }else{
            ctx.body={
                code:"1002",
                msg:"邮箱发送失败"
            }
        }
    }

    async getAccess(){
        const {ctx}=this
        const {access_token}=ctx.request.query;
        const result=await ctx.service.codes.getAccess(access_token)
        if(result.status==200){
            const token=createToken(result.data.name)
            ctx.body={
                code:"1001",
                msg:"获取用户信息成功",
                result:result.data,
                token
            }
        }else{
            ctx.body={
                code:"1002",
                msg:"获取用户信息失败"
            }
        }
    }

    async getCodegit(){
        const {ctx}=this
        const {gitcode}=ctx.request.query
        const result=await ctx.service.codes.getCodegit(gitcode)
        if(result.status==200){
            ctx.body={
                code:"1001",
                msg:"获取access_token成功",
                access_token:result.data.access_token,
                isAbandon:true
            }
        }else{
            ctx.body={
                code:"1002",
                msg:"获取access_token失败",
                isAbandon:true
            }
        }
    }
}

module.exports=codeController